package com.briup.pts.service.impl;

import com.briup.pts.config.property.NginxProperty;
import com.briup.pts.service.UploadService;
import com.briup.pts.utils.UuidUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

@Service
@RequiredArgsConstructor
public class UploadServiceImpl implements UploadService {

    private final NginxProperty property;

    @Override
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        // 生成新的文件名
        String fileName = generatorFileName(originalFilename);
        // 进行文件传输
        try (BufferedOutputStream fos = new BufferedOutputStream(
                new FileOutputStream(String.format(property.getPath(),fileName)))) {
            // 将数据写出
            file.getInputStream().transferTo(fos);
            // 返回url地址
            return String.format(property.getUrl(),fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据文件的原始名称，文件后缀不变的情况下，将文件名修改为唯一的名称
     * @param originalFilename 原始文件名
     * @return 新文件名
     */
    private String generatorFileName(String originalFilename){
        // a.txt.png
        String suffix = originalFilename.substring(
                originalFilename.lastIndexOf("."));
        return UuidUtil.generator()+suffix;
    }
}
